package com.lcm.basic.p7.set;

import com.lcm.basic.p7.set.bean.Person;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author Coder-lcm
 * @date 2021/4/3
 *
 *   注意当set的对象时可变对象时，如果set中的元素对应的引用地址对象，被修改，有可能会导致set出现重复元素的情况，这将导致HashSet不可能准确的访问该元素
 */
public class SetDemoForHashSet2 {
    int count;
    public SetDemoForHashSet2(int count) {
        this.count = count;
    }

    @Override
    public String toString() {
        return "SetDemoForHashSet2{" +
                "count=" + count +
                '}';
    }

    @Override
    public boolean equals(Object o) {
       if (o instanceof SetDemoForHashSet2) {
           SetDemoForHashSet2 t = (SetDemoForHashSet2) o;
           if (t.count == this.count) {
               return true;
           }
       }
        return false;
    }

    @Override
    public int hashCode() {
        return this.count;
    }

    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add(new SetDemoForHashSet2(5));
        hs.add(new SetDemoForHashSet2(-3));
        hs.add(new SetDemoForHashSet2(9));
        hs.add(new SetDemoForHashSet2(-2));
        System.out.println(hs); // [SetDemoForHashSet2{count=-2}, SetDemoForHashSet2{count=-3}, SetDemoForHashSet2{count=5}, SetDemoForHashSet2{count=9}]
        // 取出集合的第一个元素
        SetDemoForHashSet2 first = (SetDemoForHashSet2) hs.iterator().next();
        // 并修改属性值为 -3
        first.count = -3;
        System.out.println(hs);// 发现set里含有了重复元素： [SetDemoForHashSet2{count=-3}, SetDemoForHashSet2{count=-3}, SetDemoForHashSet2{count=5}, SetDemoForHashSet2{count=9}]

        //删除属性count为-3的对象
        hs.remove(new SetDemoForHashSet2(-3));
        System.out.println(hs); //[SetDemoForHashSet2{count=-3}, SetDemoForHashSet2{count=5}, SetDemoForHashSet2{count=9}]

        System.out.println("set exist a element count == -3 ? "+  hs.contains(new SetDemoForHashSet2(-3))); //false
        System.out.println("set exist a element count == -2 ? "+  hs.contains(new SetDemoForHashSet2(-2))); //false

    }
}
